package com.cmwa.scbp.base.config.dataSource;

import javax.sql.DataSource;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.boot.autoconfigure.SpringBootVFS;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;

@Configuration
@AutoConfigureBefore(MapperScanner.class)
public class DbInject {

	@Primary
    @Bean(initMethod = "init",name = "scbpDataSource")
    @ConfigurationProperties("spring.datasource.druid.scbp")
    public DataSource dataSource(){
        return DruidDataSourceBuilder.create().build();
    }
	
	@Bean(name = "scbpSqlSessionFactory")
    @Primary
    public SqlSessionFactory sqlSessionFactory(@Qualifier("scbpDataSource") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        bean.setVfs(SpringBootVFS.class);
        bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath*:mappers/**/*.xml"));
        bean.setConfigLocation(new PathMatchingResourcePatternResolver().getResource("classpath:mybatis.xml"));
        bean.setTypeAliasesPackage("com.cmwa.scbp");
        
        return bean.getObject();
    }

    @Bean(name = "scbpTransactionManager")
    @Primary
    public DataSourceTransactionManager transactionManager(@Qualifier("scbpDataSource") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

    @Bean(name = "scbpSqlSessionTemplate")
    @Primary
    public SqlSessionTemplate scbpSqlSessionTemplate(@Qualifier("scbpSqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
        return new SqlSessionTemplate(sqlSessionFactory);
    }
}
